<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/11/13 14:47
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Api\V1\App\Common;

use App\Http\Controllers\ApiController;
use App\Models\Customers\Customer;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;

class CustomerTokenController extends ApiController
{
    const CACHE_KEY_JWT_TOKEN_FORMAT = "dw-customer:%s:jwt-token";

    /**
     * 刷新并缓存 jwt Token 给 OpenCart 的页面使用
     *
     * @param $customer_id
     *
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiAbstractException
     */
    public function regenerateJwt($customer_id)
    {
        $cache_key = sprintf(self::CACHE_KEY_JWT_TOKEN_FORMAT, $customer_id);
        if (cache($cache_key)) {
            return $this->responseAccepted(['cached' => true]);
        }

        /** @var Customer $customer */
        $customer = (new Customer)->whereKey($customer_id)->first();
            $this->checkItemExist($customer, "customer id:$customer_id");

        /** @var JWTGuard $jwt */
        $jwt = Auth::guard(Customer::GUARD_NAME);
        $ttl = 1440; // one day min
        $token = $jwt->setTTL($ttl)->tokenById($customer_id);
            cache([$cache_key => $token], $ttl);

        $updated = $customer->updateJwtToken($token);

        return $this->responseAccepted(compact('updated'));
    }
}